//
//  EnergyManager.m
//  BreakPieces
//
//  Created by Test on 11/2/14.
//  Copyright (c) 2014 Stefan.Nestorov. All rights reserved.
//

#import "EnergyManager.h"
#import "Globals.h"

@interface EnergyManager () {
    
    NSTimer *_internalTimer;
    NSInteger _maxEnergy;
    NSInteger _timeToReplanishEnergy;
    
}

@end

@implementation EnergyManager

- (instancetype)init
{
    
    self = [super init];
    
    if ( self != nil ) {
        
        NSUserDefaults *settings = [NSUserDefaults standardUserDefaults];
        [settings setObject:@(5) forKey:MAX_ENERGY_KEY];
        
        if ( [settings objectForKey:CURRENT_ENERGY_KEY] == nil ) {
//#warning set 5 Energy in Production !
            [settings setObject:@(5) forKey:CURRENT_ENERGY_KEY];
            [settings setObject:[NSDate date] forKey:LAST_ENERGY_REPLENISHMENT_DATE_KEY];
            
        }
        
        if ( [settings boolForKey:@"isIncreasedStorageSize"] == YES ) {
            [settings setObject:@(INCREASED_STORAGE_SIZE) forKey:MAX_ENERGY_KEY];
        }
        
        [settings synchronize];
        
        _timeToReplanishEnergy = 0;
        _maxEnergy = [[settings objectForKey:MAX_ENERGY_KEY] integerValue];
        _internalTimer = [NSTimer timerWithTimeInterval:1.0f target:self selector:@selector(timerUpdate) userInfo:nil repeats:YES];
        [[NSRunLoop mainRunLoop] addTimer:_internalTimer forMode:NSDefaultRunLoopMode];
        NSLog(@"Energy manager boot");
    }
    
    return self;
        
}

+ (instancetype)sharedInstance
{
    
    static EnergyManager *sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[EnergyManager alloc] init];
    });
    
    return sharedInstance;
    
}

- (void)timerUpdate
{
    
    NSUserDefaults *settings = [NSUserDefaults standardUserDefaults];
    
    if ( [settings boolForKey:@"isIncreasedStorageSize"] == YES && _maxEnergy < INCREASED_STORAGE_SIZE ) {
        _maxEnergy = INCREASED_STORAGE_SIZE;
    }
    
    NSInteger energy = [self energy];
    
    if ( energy < _maxEnergy ) {
        NSDate *lastReplenishment = [settings objectForKey:LAST_ENERGY_REPLENISHMENT_DATE_KEY];
        if ( lastReplenishment == nil ) {
            lastReplenishment = [NSDate dateWithTimeIntervalSince1970:0];
            NSLog(@"No last replenishment data found.");
        }
        
        NSTimeInterval diff = [[NSDate date] timeIntervalSinceDate:lastReplenishment];
        NSInteger absoluteDifference = (NSInteger)fabs(diff);
        
        if ( absoluteDifference >= TIME_TO_SPAWN_ENERGY ) {
            // replenish energy
            NSInteger energyCount = absoluteDifference / TIME_TO_SPAWN_ENERGY;
            
            // do not exceed max Energy
            // if this check is not here, the life count for first life would be an enormous number
            // possibly leading to a hang
            if ( energyCount > _maxEnergy ) {
                energyCount = _maxEnergy;
            }
            
            for (NSInteger i = 0; i < energyCount; ++i) {
                [self replenishEnergy];
            }
        } else {
            
            _timeToReplanishEnergy = TIME_TO_SPAWN_ENERGY - absoluteDifference;
            
        }
    }
    
}

- (void)replenishEnergy
{
    
    NSUserDefaults *settings = [NSUserDefaults standardUserDefaults];
    NSInteger energy = [self energy];
    
    if ( energy < _maxEnergy ) {
        energy++;
        
        NSLog(@"Energy replenishment");
        [settings setObject:@(energy) forKey:CURRENT_ENERGY_KEY];
        [settings setObject:[NSDate date] forKey:LAST_ENERGY_REPLENISHMENT_DATE_KEY];
        [settings synchronize];
        
        [[NSNotificationCenter defaultCenter] postNotificationName:kEnergyManagerEnergyReplenished object:nil];
    }
    
}

-(NSInteger)energy
{
    
    NSUserDefaults *settings = [NSUserDefaults standardUserDefaults];
    
    return [[settings objectForKey:CURRENT_ENERGY_KEY] integerValue];
    
}


- (NSString *)getTimeToReplanishEnergy
{
    
    NSInteger seconds = _timeToReplanishEnergy % 60;
    NSInteger minutes = (_timeToReplanishEnergy / 60) % 60;
    
    NSString *timeToReplanishEnergy;
    
    if ( seconds % 2 == 0 ) {
        
        timeToReplanishEnergy = [NSString stringWithFormat:@"%01zd:%02zd", minutes, seconds];
        
    } else {
        
        timeToReplanishEnergy = [NSString stringWithFormat:@"%01zd %02zd", minutes, seconds];
        
    }
    
    return timeToReplanishEnergy;
    
}


@end
